#!/bin/bash

# Uninstall script for Debug Utilities
# This script removes the installed files from the system

# Default installation prefix
PREFIX="/usr/local"

# Allow override of prefix via command line argument
if [ $# -eq 1 ]; then
    PREFIX="$1"
    echo "Using custom prefix: $PREFIX"
else
    echo "Using default prefix: $PREFIX"
    echo "You can specify a custom prefix with: $0 /path/to/installation"
fi

# Check if the user has permissions to remove files from the prefix
if [ ! -w "$PREFIX" ]; then
    echo "Warning: You may need sudo permissions to uninstall from $PREFIX"
    echo "Attempting to use sudo..."
    SUDO="sudo"
else
    SUDO=""
fi

# List of files and directories to remove
FILES=(
    "$PREFIX/lib/libcdebug_utils.so"
    "$PREFIX/lib/libcdebug_utils.a"
    "$PREFIX/lib/libcudadebug_utils.so"
    "$PREFIX/lib/libcudadebug_utils.a"
    "$PREFIX/lib/libfdebug_utils.a"
    "$PREFIX/include/debug_utils.h"
    "$PREFIX/include/debug_utils.mod"
    "$PREFIX/bin/compare_norm.py"
    "$PREFIX/bin/compare_norm_simple.sh"
)

# Counter for removed files
REMOVED=0

# Remove each file if it exists
echo "Removing installed files..."
for FILE in "${FILES[@]}"; do
    if [ -f "$FILE" ] || [ -L "$FILE" ]; then
        echo "Removing: $FILE"
        $SUDO rm -f "$FILE"
        if [ $? -eq 0 ]; then
            ((REMOVED++))
        else
            echo "Failed to remove: $FILE"
        fi
    else
        echo "Not found: $FILE (skipping)"
    fi
done

# Check if include directory is empty and remove it if so
INCLUDE_DIR="$PREFIX/include"
if [ -d "$INCLUDE_DIR" ]; then
    if [ -z "$(ls -A "$INCLUDE_DIR")" ]; then
        echo "Removing empty include directory: $INCLUDE_DIR"
        $SUDO rmdir "$INCLUDE_DIR"
    else
        echo "Include directory not empty, leaving: $INCLUDE_DIR"
    fi
fi

# Check if lib directory is empty and remove it if so
LIB_DIR="$PREFIX/lib"
if [ -d "$LIB_DIR" ]; then
    if [ -z "$(ls -A "$LIB_DIR")" ]; then
        echo "Removing empty lib directory: $LIB_DIR"
        $SUDO rmdir "$LIB_DIR"
    else
        echo "Lib directory not empty, leaving: $LIB_DIR"
    fi
fi

# Check if bin directory is empty and remove it if so
BIN_DIR="$PREFIX/bin"
if [ -d "$BIN_DIR" ]; then
    if [ -z "$(ls -A "$BIN_DIR")" ]; then
        echo "Removing empty bin directory: $BIN_DIR"
        $SUDO rmdir "$BIN_DIR"
    else
        echo "Bin directory not empty, leaving: $BIN_DIR"
    fi
fi

echo ""
echo "Uninstall complete. Removed $REMOVED files."
if [ $REMOVED -eq 0 ]; then
    echo "Note: No files were found to remove. Check if the prefix is correct."
fi

echo "If any directories were not removed, it is because they still contain other files."
exit 0 